package com.ThreadSyncEg;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;

//并发修改Set集合
public class ConcurrentHashMapDemo {
    public static void main(String[] args) {
        //hashSet是一个不允许有重复元素的集合。 允许有 null 值。是无序的
//        Set<String> hashSet = new HashSet<>(); 并发修改会异常 不安全
//        Set<String> hashSet = Collections.synchronizedSet(new HashSet<>());//锁set
        //读写分离Set集合 安全
        Set<String> hashSet = new CopyOnWriteArraySet<>();

        //Map
        ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();

        for (int i = 0; i < 20; i++) {
            new Thread(()->{
                //set
//                hashSet.add(UUID.randomUUID().toString().substring(1,5));
                //并发map
                concurrentHashMap.put(
                        Thread.currentThread().getName(),UUID.randomUUID().toString().substring(1,5));

                System.out.println(concurrentHashMap+"----");
            },String.valueOf(i)).start();
        }
    }
}
